<template xmlns="http://www.w3.org/1999/html">
  <a-spin :spinning="confirmLoading">
    <!--引用表格-->
    <BasicTable @register="registerTable" :expandedRowKeys="expandedRowKeys"  @expand="handleExpand">
      <!-- 内嵌table区域 begin -->
      <template #expandedRowRender="{record}">
        <caishuiTaskSettleItemSubTable :id="expandedRowKeys[0]"/>
      </template>
      <!-- 内嵌table区域 end -->
      <!--插槽:table标题-->
      <template #tableTitle>
<!--        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">结算单导入</j-upload-button>-->
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="handleAdd">结算单导入</a-button>
        <a href="javascript:void(0)" @click="handleTemplateDownload" style="margin: 8px;"><Icon icon="ant-design:download-outlined" /> 结算单导入模板</a>
<!--        <br>
        <a-alert style="margin-left: 20px;" message="发放限工作日9:00～18:00之间，预计5分钟内到账；非工作日和国家规定节假日期间无法发放。" type="error" show-icon >
          <template #icon><exclamation-circle-outlined /></template>
        </a-alert>-->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--总数插槽-->
      <template #totalSlot="{record}">
        <span style="text-align: left;">
          <p>总金额：<span style="font-weight: bold;">{{record.totalAmount.toFixed(2)}}</span></p>
          <p>总笔数：<span style="font-weight: bold;">{{record.totalNum}}</span></p>
        </span>
      </template>
      <template #successSlot="{record}">
        <span style="text-align: left;">
          <p>成功金额：<span style="font-weight: bold;color: red;">{{record.successAmount.toFixed(2)}}</span></p>
          <p>成功笔数：<span style="font-weight: bold;">{{record.successNum}}</span></p>
        </span>
      </template>
      <template #failSlot="{record}">
        <span style="text-align: left;">
          <p>失败金额：<span style="font-weight: bold;">{{record.failAmount.toFixed(2)}}</span></p>
          <p>失败笔数：<span style="font-weight: bold;">{{record.failNum}}</span></p>
        </span>
      </template>
      <template #serviceFeeSlot="{record}">
        <span style="text-align: left;">
          <p>总金额：<span style="font-weight: bold;">{{record.serviceFee.toFixed(2)}}</span></p>
          <p>成功金额：<span style="font-weight: bold;">{{record.successServiceFee.toFixed(2)}}</span></p>
        </span>
      </template>
      <!--状态插槽-->
      <template #statusSlot="{record}">
        <a-tag v-if="record.status==0" color="blue">{{record.status_dictText}}</a-tag>
        <a-tag v-if="record.status==1" color="cyan">{{record.status_dictText}}</a-tag>
        <a-tag v-if="record.status==2" color="green">{{record.status_dictText}}</a-tag>
        <a-tag v-if="record.status==3" color="red">{{record.status_dictText}}</a-tag>
        <a-tag v-if="record.status==4" color="grey">{{record.status_dictText}}</a-tag>
      </template>
      <!--发放插槽-->
      <template #extendStatusSlot="{record}">
        <a-badge v-if="record.extendStatus==0" color="blue" :text="record.extendStatus_dictText" />
        <a-badge v-if="record.extendStatus==1" color="cyan" :text="record.extendStatus_dictText" />
        <a-badge v-if="record.extendStatus==2" color="green" :text="record.extendStatus_dictText" />
        <a-badge v-if="record.extendStatus==3" color="red" :text="record.extendStatus_dictText" />
      </template>
      <!--文件插槽-->
      <template #fileSlot="{text}">
        <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
        <span v-else>
          <a-button :ghost="true" type="primary" preIcon="ant-design:search-outlined" size="small" @click="viewFile(text)">预览</a-button>
          <br/>
          <a-button style="margin-top: 10px;" :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
        </span>
      </template>
    </BasicTable>
    <!--明细抽屉-->
    <CaishuiTaskSettleItemDrawer @register="registerDrawer" />
    <!-- 验证手机区域 -->
    <VerifyPhone ref="registerVerifyPhone" @success="handleVerifyPhoneSuccess"></VerifyPhone>
    <!--导入表单-->
    <TaskSettleItemBatchImport ref="registerBatchImportModal" @success="handleSuccess"></TaskSettleItemBatchImport>
  </a-spin>
</template>

<script lang="ts" name="caishuiTaskSettle-caishuiTaskSettle" setup>
import { ref } from "vue";
import { BasicTable, TableAction } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import CaishuiTaskSettleItemSubTable from "./subTables/CaishuiTaskSettleItemSubTable.vue";
import CaishuiTaskSettleItemDrawer from "./components/CaishuiTaskSettleItemDrawer.vue";
import TaskSettleItemBatchImport from "./components/TaskSettleItemBatchImport.vue";
import VerifyPhone from "/@/layouts/default/header/components/user-dropdown/VerifyPhone.vue";
import { columns, searchFormSchema } from "./CaishuiTaskSettle.data";
import { getExportUrl, getImportUrl, list, statusOne } from "./CaishuiTaskSettle.api";
import { downloadFile, viewFile } from "/@/utils/common/renderUtils";
import { useGlobSetting } from "/@/hooks/setting";
import { useDrawer } from "/@/components/Drawer";
import {useMessage} from '/@/hooks/web/useMessage';

// 展开key
const expandedRowKeys = ref<any[]>([]);
const glob = useGlobSetting();
const { createMessage } = useMessage();
const registerVerifyPhone = ref();
const registerBatchImportModal = ref();
const confirmLoading = ref<boolean>(false);
//注册drawer
const [registerDrawer, { openDrawer }] = useDrawer();
//注册table数据
const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
  tableProps:{
    title: '任务结算',
    api: list,
    columns,
    canResize:false,
    striped: true,
    // showIndexColumn: true,
    ellipsis: false,
    formConfig: {
      labelWidth: 80,
      schemas: searchFormSchema,
      autoSubmitOnEnter:true,
      showAdvancedButton:true,
      autoAdvancedCol: 2,
      autoAdvancedLine: 2,
      fieldMapToNumber: [
        ['totalAmount', ['totalAmount_begin', 'totalAmount_end']],
        ['totalNum', ['totalNum_begin', 'totalNum_end']],
      ],
      fieldMapToTime: [
        ['createTime', ['createTime_begin', 'createTime_end'], 'YYYY-MM-DD HH:mm:ss'],
        ['submitTime', ['submitTime_begin', 'submitTime_end'], 'YYYY-MM-DD HH:mm:ss'],
        ['checkTime', ['checkTime_begin', 'checkTime_end'], 'YYYY-MM-DD HH:mm:ss'],
      ],
    },
    actionColumn: {
      width: 150,
      fixed:'right'
    },
    beforeFetch: (params) => {
      // console.log("===查询条件===:",params)
    },
  },
  exportConfig: {
    name:"任务结算",
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

/**
 * 结算单导入事件
 */
function handleAdd() {
  registerBatchImportModal.value.add();
}

/**
 * 展开事件
 * */
function handleExpand(expanded, record){
  expandedRowKeys.value=[];
  if (expanded === true) {
    expandedRowKeys.value.push(record.id)
  }
}

/**
 * 明细事件
 */
function handleList(record: Recordable) {
  openDrawer(true, {
    record,
  });
}

/**
 * 提交
 */
function handleSubmitJs(record: Recordable) {
  if(record.submitStatus == 3){
    createMessage.error("下发人员名单中存在超过限制金额人员，无法下发！");
  }else {
    registerVerifyPhone.value.show(record.id,1);
  }
}

/**
 * 验证手机完成之后提交事件
 */
async function handleVerifyPhoneSuccess(data) {
  confirmLoading.value = true;
  await statusOne({
    id: data.id,
    status: data.status,
    captcha: data.captcha }).then((res) => {
    if (res.success) {
      createMessage.success(res.message);
      handleSuccess();
    } else {
      createMessage.warning(res.message);
    }
  }).finally(() => {
    confirmLoading.value = false;
  });
}

/**
 * 作废事件
 */
async function handleStatus(record,status) {
  confirmLoading.value = true;
  await statusOne({
    id: record.id,
    status: status }).then((res) => {
    if (res.success) {
      createMessage.success(res.message);
      handleSuccess();
    } else {
      createMessage.warning(res.message);
    }
  }).finally(() => {
    confirmLoading.value = false;
  });
}

/**
 * 成功回调
 */
function handleSuccess() {
  confirmLoading.value = false;
  (selectedRowKeys.value = []) && reload();
}
/**
 * 操作栏
 */
function getTableAction(record){
  return [
    {
      label: '提交',
      ifShow: record.status == 0 && record.submitStatus == 1,
      icon: 'ant-design:check-circle-outlined',
      popConfirm: {
        title: '请仔细检查数据，确认无误后将直接下发！',
        confirm: handleSubmitJs.bind(null, record,1),
      }
    },
    {
      label: '提交',
      ifShow: record.status == 0 && record.submitStatus == 2,
      icon: 'ant-design:check-circle-outlined',
      popConfirm: {
        title: '下发人员名单中存在超过限制金额人员，待审核后下发！',
        confirm: handleSubmitJs.bind(null, record,1),
      }
    },
    {
      label: '提交',
      ifShow: record.status == 0 && record.submitStatus == 3,
      icon: 'ant-design:check-circle-outlined',
      onClick: handleSubmitJs.bind(null, record,1),
    },
    {
      label: '发放明细',
      ifShow: record.status != 0,
      icon: 'ant-design:unordered-list-outlined',
      onClick: handleList.bind(null, record),
    }
  ]
}

/**
 * 下拉操作栏
 */
function getDropDownAction(record){
  return [
    {
      label: '发放明细',
      ifShow: record.status == 0,
      icon: 'ant-design:unordered-list-outlined',
      onClick: handleList.bind(null, record),
    }, {
      label: '作废',
      ifShow: record.status == 0,
      icon: 'ant-design:delete-outlined',
      popConfirm: {
        title: '是否确认作废？',
        confirm: handleStatus.bind(null, record,4),
      }
    }
  ]
}

/**
 * 结算单导入模板下载
 */
function handleTemplateDownload() {
  let url = glob.filePreviewUrl + "miniofile/templateFile/结算单导入模板.xls";
  window.open(url, '_blank');
}

</script>

<style scoped>

</style>
